var config = {
	get_fail_list : ctx + "conweb/get_fail_list",
	get_regular_list : ctx + "conweb/get_regular_list",//entryId=502
	get_html_list : ctx + "conweb/get_html_list",//entryId=502&errorCode=5
	get_statistics_list : ctx + "conweb/get_statistics_list",
	save_regular : ctx + "conweb/save_regular",
	update_regular : ctx + "conweb/update_regular",
	remove_regular : ctx + "conweb/remove_regular",
	update_status : ctx + "conweb/update_status",
	remove_fail_htmls: ctx + "conweb/remove_fail_htmls",
	get_entry_list: ctx + "conweb/get_entry_list",
	remove_batch : ctx + "conweb/remove_batch"
};

var failTable = null;
var regularTable = null;
var htmlTable = null;
var entryIds = null;
var globalEntryId = null;
var globalErrorCode = null;




var dbType = GetQueryString("dbType");
if(dbType==-1){
	dbType=$("#db").val();
}else{
	$("#db").val(dbType);
}

$("#commit").attr("type","0");
failList();
$("#db").change(function(){
	dbType = $("#db").val();
	failList();
});



//0
function failList(){
	$.ajax({
		cache : false,
		type : "GET",
		url : config.get_fail_list,
		data : {dbType:dbType},
		async : true,
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data){
			failTab(data);
			//2
			regularList(data[0].entryId, data[0].entryName, data[0].error, data[0].errorCode, data[0].entryUrl, data[0].sourceid);
		}
	});
	
}
//0
function failTab(tableData) {
	if(failTable != null){
		failTable = $("#failTab").bootstrapTable('destroy');
	}
	failTable = $('#failTab').bootstrapTable({
        data:tableData,
        height:1407,
        search:true, 
        iconSize: 'outline',
        striped: true, // 设置为true会有隔行变色效果
        cache: false,  
        pagination: false, // 设置为true会在底部显示分页条
        // queryParamsType : "limit",
        //设置为limit则会发送符合RESTFull格式的参数
        singleSelect: false, // 设置为true将禁止多选
        // contentType : "application/x-www-form-urlencoded",
        //发送到服务器的数据编码类型
        pageSize: 1000, // 如果设置了分页，每页数据条数
        pageNumber: 1, // 如果设置了分布，首页页码
        // search : true, // 是否显示搜索框
        // showColumns : true, // 是否显示内容下拉框（选择显示的列）
        sidePagination: "client", // 设置在哪里进行分页，可选值为"client" 或者
        onAll: function (name, args) {
        	//全部加载完成后执行
            return false;
        },
        columns: [
            {
                title: '网站名称',
                align: 'center',
                field: 'entryId',
                formatter : function(value, row, index) {
                	var temp;
                	if(row.entryName=='' || row.entryName==null){
                		return '';
                	}
                	var title = row.entryName.replace(/"/g,"");
                	if(title.length>6){
                		temp = title.substring(0, 4) + "..."
                	}else{
                		temp = title;
                	}
					return '<a href="#" entryId='+ row.entryId +' sourceid='+ row.sourceid +' entryUrl='+ row.entryUrl +' errorCode='+ row.errorCode +' error='+ row.error +' title="' +title+'" onclick="transReg(this)">' +temp+'</a> ';
				}
            },
            {
				title : '错误类型',
				align : 'center',
				sortable:true,
				field: 'error'
			},
            {
                title: '错误数',
                align: 'center',
                sortable:true,
                field: 'n'
            }]
    });
}
//1
function transReg(t){
	var entryId = $(t).attr("entryId");
	var title = $(t).attr("title");
	var errorCode = $(t).attr("errorCode");
	var error = $(t).attr("error");
	var entryUrl = $(t).attr("entryUrl");
	var sourceid = $(t).attr("sourceid");
	regularList(entryId, title, error, errorCode, entryUrl, sourceid);
	
}
//3
function regularList(entryId, title, error, errorCode, entryUrl, sourceid){
	$("#regularTitle").html("解析规则:<a href='"+entryUrl+"' target='_blank'>" + title +"</a>_"+entryId);
	$("#sourTitle").html("sourceid_"+sourceid);
	//$("#htmlTitle").html("页面内容列表:" + title+"-<span style='color:red'>(" +error+ ")</span>");
	globalEntryId = entryId;
	globalErrorCode = errorCode;
	entryList(sourceid);
	regularData(entryId);
	htmlList(entryId, title, errorCode);
}
//4
function regularData(entryId){
	$.ajax({
		cache : false,
		type : "GET",
		url : config.get_regular_list,
		data : { 
			entryId:entryId,
			dbType:dbType
		},
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data){
			regularTab(data);
		}
	});
}
//3
function entryList(sourceid){
	$.ajax({
		cache : false,
		type : "GET",
		url : config.get_entry_list,
		data : {
			sourceid: sourceid,
			dbType: dbType
			},
		async : true,
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data){
			entryIds='';
			var entryHtm ="";
			var entryList = $("#entryList");
			if(data){
				for (var i = 0; i < data.length; i++) {
					var item = data[i];
					entryIds+= item.entryId+','
					entryHtm +="<option url="+item.entryUrl+" value='" + item.entryId + "'>" + item.entryName + "</option>";
				}
			}
			entryList.html(entryHtm);
		}
	});
}

$("#entryList").click(function(){
	var entryId = $("#entryList").val();
	var title = $("#entryList option:selected").text();
	var entryUrl = $("#entryList option:selected").attr("url");
	$("#regularTitle").html("解析规则:<a href='"+entryUrl+"' target='_blank'>" + title +"</a>_"+entryId);
	regularData(entryId);
	globalEntryId = entryId;
	globalErrorCode = null;
	htmlList(entryId, title, null);
});

function regularTab(tableData) {
	if(regularTable != null){
		regularTable = $("#regularTab").bootstrapTable('destroy');
	}
	regularTable = $('#regularTab').bootstrapTable({
        data:tableData,
        height:235,
        iconSize: 'outline',
        striped: true, // 设置为true会有隔行变色效果
        cache: false,  
        pagination: false, // 设置为true会在底部显示分页条
        // queryParamsType : "limit",
        //设置为limit则会发送符合RESTFull格式的参数
        singleSelect: false, // 设置为true将禁止多选
        // contentType : "application/x-www-form-urlencoded",
        //发送到服务器的数据编码类型
        pageSize: 200, // 如果设置了分页，每页数据条数
        pageNumber: 1, // 如果设置了分布，首页页码
        // search : true, // 是否显示搜索框
        // showColumns : true, // 是否显示内容下拉框（选择显示的列）
        sidePagination: "client", // 设置在哪里进行分页，可选值为"client" 或者"server"
        columns: [
            {
                title: '说明',
                align: 'center',
                formatter : function(value, row, index) {
                	var temp;
                	if(row.desc=='' || row.desc==null){
                		return '';
                	}
                	var title = row.desc.replace(/"/g,'');
                	if(title.length>12){
                		temp = title.substring(0, 10) + "..."
                	}else{
                		temp = title;
                	}
					return '<a href="#" regularId='+ row.regularId +' title="' +title+'" onclick="dealRegular(this)">' +temp+'</a> ';
				}
            },
            {
				title : '选择器',
				align : 'center',
				formatter : function(value, row, index) {
                	var temp;
                	if(row.select=='' || row.select==null){
                		return '';
                	}
                	var title = row.select;
                	if(title.length>70){
                		temp = title.substring(0, 67) + "..."
                	}else{
                		temp = title;
                	}
					return '<span title="' +title+'">' +temp+'</span> ';
				}
			},
            {
				title : '属性',
				align : 'center',
				field: 'attr'
			},
			{
				title : '正则',
				align : 'center',
				field: 'regex'
			},
			{
				title : '所属类型',
				sortable:true,
				align : 'center',
				field: 'regulartype'
			},
			{
				title : '数据类型',
				sortable:true,
				align : 'center',
				field: 'fieldtype'
			},
            {
                title: '日期格式',
                align: 'center',
                field: 'dateformat'
            },{
				title : '',
				align : 'center',
				formatter : function(value, row, index) {
					return '<a class="btn btn-warning btn-xs" href="#" title="删除"  mce_href="#" onclick="removeRegular('
						+ row.regularId+','+row.entryId+ ')"><i class="fa fa-remove"></i></a> ';
				}
			}]
    });
}
//4
function htmlList(entryId, title, errorCode){
	$("#refresh").addClass("fa-spin");
	if(title){
		$("#htmlTitle").html("页面内容列表:" + title);
	}
	if(typeof(entryId) == 'undefined'){
		entryId =  globalEntryId;
	}
	if(typeof(errorCode) == 'undefined'){
		errorCode =  globalErrorCode;
	}
	$.ajax({
		cache : false,
		type : "GET",
		url : config.get_html_list,
		data : { 
			entryId:entryId,
			errorCode:errorCode,
			dbType:dbType
		},
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data){
			htmlTab(data.htmls);
			$("#wrongTotal").html(" (错误总数:" + data.total+")");
			$("#refresh").removeClass("fa-spin");
		}
	});
}

function htmlTab(tableData) {
	if(htmlTable != null){
		htmlTable = $("#htmlTab").bootstrapTable('destroy');
	}
	htmlTable = $('#htmlTab').bootstrapTable({
        data:tableData,
        iconSize: 'outline',
        striped: true, // 设置为true会有隔行变色效果
        cache: false,  
        pagination: false, // 设置为true会在底部显示分页条
        // queryParamsType : "limit",
        //设置为limit则会发送符合RESTFull格式的参数
        singleSelect: false, // 设置为true将禁止多选
        // contentType : "application/x-www-form-urlencoded",
        //发送到服务器的数据编码类型
        pageSize: 25, // 如果设置了分页，每页数据条数
        pageNumber: 1, // 如果设置了分布，首页页码
        // search : true, // 是否显示搜索框
        // showColumns : true, // 是否显示内容下拉框（选择显示的列）
        sidePagination: "client", // 设置在哪里进行分页，可选值为"client" 或者"server"
        columns: [{
				checkbox: true
			},
            {
                title: '链接',
                align: 'center',
                formatter : function(value, row, index) {
                	var temp;
                	if(row.url.length>70){
                		temp = row.url.substring(0, 67) + "..."
                	}else{
                		temp = row.url;
                	}
					return '<a href="'+row.url+'" target="_blank">' +temp+'</a> ';
				}
            },{
				title : '错误类型',
				sortable:true,
				align : 'center',
				field: 'error'
			},
            {
				title : '页面大小',
				sortable:true,
				align : 'center',
				field: 'pagesize'
			},
			{
				title : '时间',
				align : 'center',
				sortable:true,
				field: 'localtm'
			},
			{
				title : '抓取页面',
				align : 'center',
				formatter : function(value, row, index) {
                	var temp;
                	if(row.url.length>70){
                		temp = row.url.substring(0, 67) + "..."
                	}else{
                		temp = row.url;
                	}
					return '<a href="'+ctx+'sourhtml?urlid='+row.urlid+'&dbType='+dbType+'" target="_blank">查看</a> ';
				}
			}]
    });
}

function resetEntry(){
	$.ajax({
		cache : false,
		type : "post",
		url : config.update_status,
		data : { 
			entryId: globalEntryId,
			errorCode: globalErrorCode,
			dbType: dbType
		},
		error : function(request) {
			layer.alert("Connection error");
		},
		success : function(data){
			layer.alert(data.msg);
		}
	});
}

function dealRegular(t){
	if(t){
		$("#sourceDiv").hide();
		var regularId = $(t).attr("regularId");
		$("#editTitle").html("修改解析");
		$("#commit").attr("type",regularId);
		
		$.ajax({
			cache : false,
			type : "GET",
			url : config.get_regular_list,
			data : { 
				regularId: $(t).attr("regularId"),
				dbType: dbType
			},
			error : function(request) {
				layer.alert("Connection error");
			},
			success : function(data){
				var item = data[0];
				//console.info(item);
				$("#select").val(item.select);
				$("#attr").val(item.attr);
				$("#regex").val(item.regex);
				//$("#regulartype").selectpicker('val', item.regulartype);
				//$("#selectorType").selectpicker('val', item.selectorType);
				//$("#fieldtype").selectpicker('val', item.fieldtype);
				$("#regulartype").val(item.regulartype);
				$("#selectorType").val(item.selectorType);
				$("#desc").val(item.desc);
				$("#fieldtype").val(item.fieldtype);
				$("#dateformat").val(item.dateformat);
			}
		});
		
	}else{
		$("#sourceDiv").show();
		$("#editTitle").html("新增解析");
		$("#commit").attr("type","0");
		$("#select").val("");
		$("#attr").val("");
		$("#regex").val("");
		//$("#regulartype").selectpicker('val', null);
		//$("#selectorType").selectpicker('val', null);
		$("#desc").val($("#regulartype option:selected").text());
		//$("#fieldtype").selectpicker('val', null);
		$("#dateformat").val("");
		$("#source").attr("checked", false); 
	}
	
}

function commitForm(){
	var regularId = $("#commit").attr("type");
	var select = $("#select").val();
	var attr = $("#attr").val();
	var regex = $("#regex").val();
	var regulartype = $("#regulartype").val();
	var selectorType = $("#selectorType").val();
	var desc = $("#desc").val();
	var fieldtype = $("#fieldtype").val();
	var dateformat = $("#dateformat").val();
	
	
	
	if(select==null || select.trim()==''){
		layer.alert("选择器select不能为空！");
		return;
	}
	
	if(attr==null || attr.trim()==''){
		attr="-";
	}
	
	if(dateformat==null || dateformat.trim()==''){
		dateformat="-";
	}
	
	if(regex==null || regex.trim()==''){
		regex="-";
	}else{
		var leftSm = strCharPosition(regex, "(");
		var rightSm = strCharPosition(regex, ")");
		var leftMd = strCharPosition(regex, "[");
		var rightMd = strCharPosition(regex, "]");
		
		if((leftSm-rightSm) !=0){
			layer.alert("小括号数量不匹配！");
			return;
		}
		if((leftMd-rightMd) !=0){
			layer.alert("中括号数量不匹配！");
			return;
		}
	}
	
	var data = {
		select: select,
		attr: attr,
		regex: regex,
		regulartype: regulartype,
		selectorType: selectorType,
		desc: desc,
		fieldtype: fieldtype,
		dateformat: dateformat,
		entryId: globalEntryId,
		regularId: regularId,
		dbType: dbType
	};
	
	if(regularId==0){
		if($('#source:checked').is(':checked')){
			data.entryIds=entryIds;
		}
		$.ajax({
			cache : true,
			type : "POST",
			url : config.save_regular,
			data : data, 
			async : false,
			error : function(data) {
				layer.alert(data.msg);
			},
			success : function(data) {
				layer.alert(data.msg);
				regularData(globalEntryId);
			}
		});
		
	}else{
		$.ajax({
			cache : true,
			type : "POST",
			url : config.update_regular,
			data : data, 
			async : false,
			error : function(data) {
				layer.alert(data.msg);
			},
			success : function(data) {
				layer.alert(data.msg);
				regularData(globalEntryId);
			}
		});
	}

}


function removeRegular(regularId,entryId){
	layer.confirm('确定要删除选中的记录？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$.ajax({
			url : config.remove_regular,
			type : "post",
			data : { 
				regularId: regularId,
				dbType: dbType
			},
			success : function(r) {
				if (r.code == 0) {
					layer.msg(r.msg);
					regularData(entryId);
				} else {
					layer.msg(r.msg);
				}
			}
		});
	})
}

$("#regulartype").change(function(){
	var regulartype = $("#regulartype option:selected").text();
	$("#desc").val(regulartype);	
});

//检测一个字符在字符串中出现次数，参数字符串，一个字符，返回字符串出现的次数
function strCharPosition(str, char) {
    var pos;
    var arr = [];
    pos = str.indexOf(char);
    while (pos > -1) {
        arr.push(pos);
        pos = str.indexOf(char, pos + 1);
    }
    return arr.length;
};

function removeHtmls() {

    var rows = $('#htmlTab').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要删除的数据");
        return;
    }
    layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        var urlids = new Array();
        // 遍历所有选择的行数据，取每条数据对应的ID
        $.each(rows, function (i, row) {
            urlids[i] = row['urlid'];
        });
        $.ajax({
            type: 'POST',
            data: {
                "urlids": urlids,
                dbType: dbType
            },
            url: config.remove_fail_htmls,
            success: function (r) {
                if (r.code == 0) {
                   layer.msg(r.msg);
                   htmlList(globalEntryId, null, globalErrorCode);
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });
}

//删除当前entryId，errorCode（如果有）下全部错误html
function removeBatch() {
    layer.confirm("确认要删除全部数据吗?", {
        btn: ['确定', '取消']
        // 按钮
    }, function () {
        $.ajax({
            type: 'POST',
            data : { 
				entryId: globalEntryId,
				errorCode: globalErrorCode,
				dbType: dbType
			},
            url: config.remove_batch,
            success: function (r) {
                if (r.code == 0) {
                	htmlList(globalEntryId, null, globalErrorCode);
					layer.msg(r.msg);
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function () {
    });
}

//获取url中的参数
function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null)
		return decodeURI(r[2]);
	return -1;
}